package com.suns.controller;

import com.suns.model.SysUser;
import com.suns.service.SysUserService;
import com.suns.util.MD5Util;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

// 用户登录 ，登出
@Controller
@RequestMapping
public class UserController {
    @Resource
    private SysUserService sysUserService;
    @RequestMapping("logout.page")
    public void logout(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
        request.getSession().invalidate(); // 注销该用户session
        String path = "signin.jsp";
        response.sendRedirect(path);
    }

    @RequestMapping("login.page")
    public void login(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        String errorMsg = "";
        String ret = request.getParameter("ret");
        SysUser user=sysUserService.findByKeyword(username);
        if (StringUtils.isBlank(username)) {
            errorMsg = "用户名不能为空";
        } else if (StringUtils.isBlank(password)) {
            errorMsg = "密码不能为空";
        } else if (user == null) {
            errorMsg = "查询不到指定的用户";
        } else if (!MD5Util.encrypt(password).equals(user.getPassword())) {
            errorMsg = "密码错误";
        } else if (user.getStatus() != 1) {
            errorMsg = "用户已被冻结，请联系管理员";
        } else {
            // login 成功
            request.getSession().setAttribute("user", user);
            if (StringUtils.isNoneBlank(ret)) {
                response.sendRedirect(ret);
            } else {
                response.sendRedirect("/admin/index.page");
            }
        }

        request.setAttribute("error",errorMsg);
        request.setAttribute("username", username);
        if (StringUtils.isNotBlank(ret)) {
            request.setAttribute("ret", ret);
        }
        String path = "signin.jsp";
        request.getRequestDispatcher(path).forward(request, response);

    }

}
